using UnityEngine;
using System.Collections;
using System;

public class AnimationManager : MonoBehaviour {

	public Animations[] animationManager;
	public Renderer animationRenderer;
	public string nameAnimationPlay;
	public bool PlayAutomatically;
	Texture2D[] spriteAnim;
	string spriteName;
	bool isLoop;
	int timeRateSprite;
	int frame;
	int i;
	
	void Awake()
	{
		if(animationManager[0].sprites != null)
		{
			spriteAnim = animationManager[0].sprites;	
		}	
	}
	
	void Update()
	{
		if(PlayAutomatically)
		{
			Animate(nameAnimationPlay);	
		}
		
	}
	
	public void Animate(string animationName)
	{
		
		prepareAnim(animationName);
		frame ++;
			
		if(frame > timeRateSprite)
		{
			frame = 0;
				
			if(i > spriteAnim.Length - 1)
			{
				if(isLoop)
				i = 0;
			}
				
			animationRenderer.material.mainTexture = spriteAnim[i];
			i++;
		}

	
	}
	
	void prepareAnim(string animationName)
	{
		foreach(Animations animName in animationManager)
		{
			if(animName.nomeAnimacao == animationName)
			{
				spriteName = animationName;
				timeRateSprite = animName.timeRate;
				spriteAnim = new Texture2D[animName.sprites.Length];
				this.spriteAnim = animName.sprites;
				
				if(animName.typeAnim == Animations.wrapMod.LOOP)
				{
					isLoop = true;
				}
				
				else
				isLoop = false;
			}
		
		}
	}
	
	public void newConfig()
	{
		isLoop = false;
		i = 0;
	}
	
	public void SetFrame(int frame)
	{
		if(frame >= spriteAnim.Length)
		{
			frame = spriteAnim.Length-1;
		}
		
		animationRenderer.material.mainTexture = spriteAnim[frame];

	}

	[Serializable]
	public class Animations
	{
		public enum wrapMod
		{
			LOOP,
			ONCE
		}
		
		public wrapMod typeAnim;
		public string nomeAnimacao;
		public Texture2D[] sprites;
		public int timeRate;
	}
}
